package com.jimi.service.impl;

import com.jimi.mapper.UserMapper;
import com.jimi.pojo.User;
import com.jimi.service.UserService;
import com.jimi.utils.PasswordUtils;
import com.jimi.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User getByUserName(String username) {

        return userMapper.getByUserName(username);
    }

    @Override
    public void register(String username, String password) {

        // 使用Argon2对密码进行哈希
        String Argon2String = PasswordUtils.encode(password);
        userMapper.add(username, Argon2String);
        log.info("注册成功用户名：{}, 密码：{}", username,Argon2String);
    }

    @Override
    public User findByUserName(String username) {
        Integer id = userMapper.getIdByUserName(username);
        return userMapper.getInfoByUserId(id);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }


    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String,Object> map = ThreadLocalUtil.get();
        log.info("map：{}", map);
        Integer id = (Integer) map.get("id");
        log.info("用户id：{}", id);
        userMapper.updateAvatar(avatarUrl, id);
    }

    @Override
    public void updatePwd(String newPwd) {
        String pwd = PasswordUtils.encode(newPwd);
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updatePwd(pwd, id);
    }

}
